<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" :width="isMobile() ? '80%' : '40%'">
    <el-form ref="form" :model="formData" :rules="rules" v-loading="formLoading">
      <el-form-item prop="fileList">
        <el-upload
          style="width: 100%"
          class="upload-demo"
          drag
          :action="getAction()"
          multiple
          accept=".doc,.xls,.pdf,.xlsl,.docx,.xlsx"
          ref="uploadRef"
          :file-list="formData.fileList"
          :on-exceed="handleExceed"
          :on-change="handleChange"
          :on-remove="handleRemove"
          :before-upload="beforeUpload"
          :headers="HEADERS"
          :http-request="submitForm"
          :limit="1"
        >
          <Icon icon="ep:upload-filled" :size="50" />
          <div class="el-upload__text"> Drop file here or <em>click to upload</em> </div>
          <template #tip>
            <div style="font-size: 12px"
              >支持.doc,.xls,.pdf,.xlsl,.docx,.xlsx文件,大小不超过<b style="color: #f56c6c"
                >100MB</b
              >
            </div>
          </template>
        </el-upload>
      </el-form-item>
      <el-form-item label="任务指示" prop="tipType" label-width="80px">
        <el-select v-model="formData.tipType" placeholder="">
          <el-option label="提取客户相关信息" value="1" />
          <el-option label="提取项目相关信息" value="2" />
        </el-select>
      </el-form-item>
    </el-form>

    <template #footer>
      <p v-if="formLoading">正在解析文件,请稍后...</p>
      <el-button
        @click="analyze"
        type="primary"
        :disabled="formLoading || formData.fileList.length === 0"
      >
        提 交
      </el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import { CustomerApi } from '@/api/ai/customer'
import { FileUploadApi } from '@/api/ai/fileupload'
import { ProjectApi } from '@/api/ai/project'
import { useMessage } from '@/hooks/web/useMessage'
import { useUserStore } from '@/store/modules/user'
import { aiTips } from '@/utils/aiTips'
import { getAccessToken } from '@/utils/auth'
import { connectSSE } from '@/utils/connectSSE'
import { isMobile } from '@/utils/isMobile'
import dayjs from 'dayjs'
const userStore = useUserStore()

defineOptions({ name: 'FileUploadForm' })

const message = useMessage()
const HEADERS = { Authorization: 'Bearer ' + getAccessToken() }
const rules = {
  FileList: [
    {
      required: true,
      message: '请上传文件',
      trigger: 'blur'
    }
  ],
  tipType: [
    {
      required: true,
      message: '请选择任务指示',
      trigger: 'blur'
    }
  ]
}

const dialogVisible = ref(false)
const dialogTitle = '文件上传'
const formLoading = ref(false)
const formType = ref('')
const formData = ref({
  fileList: [] as Array<any>,
  text_input: '',
  tipType: '1'
})
const formRef = ref()
const uploadRef = ref()
const getAction = () => {
  const url = import.meta.env.VITE_BASE_URL + import.meta.env.VITE_API_URL
  return url + '/strategy/upload'
}

const handleChange = (file: any, fileList: any[]) => {
  formData.value.fileList = fileList
}

const handleRemove = (file: any, fileList: any[]) => {
  formData.value.fileList = fileList
}

const handleExceed = () => {
  // message.warning(t('onlyOneFileAllowed'))
  ElNotification({
    title: '温馨提示',
    message: `当前最多只能上传 1个文件，请移除后上传！`,
    type: 'warning'
  })
}
const newFile = ref<any>({})
const uploadFile = ref<any>([])

const emit = defineEmits(['success'])
const resetForm = () => {
  formData.value.fileList = []
  formRef.value?.resetFields()
}

const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  formType.value = type
  resetForm()
}
defineExpose({ open })

const beforeUpload = (file) => {
  const date = dayjs().valueOf()
  const newFileName = date + '_' + file.name
  const newFile1 = new File([file], newFileName, { type: file.type })
  newFile.value = newFile1
  uploadFile.value.push(newFile1)
  return true
}
const submitForm = async () => {
  if (!formData.value.fileList.length) {
    return
  }
  formLoading.value = true
  try {
    const subFormData = new FormData()
    subFormData.append('file', newFile.value)
    console.log(newFile.value)
    await FileUploadApi.aiFileUpload(subFormData)

    for (let index = 0; index < formData.value.fileList.length; index++) {
      const obj = {
        uploadUserId: userStore.user.id,
        fileList:JSON.stringify(formData.value.fileList , null, 2)
      }
      FileUploadApi.createFileUpload(obj)
    }
    message.success('上传成功')
    emit('success')
  } catch (error) {
    console.error('上传失败:', error)
    message.error('上传失败')
  } finally {
    formLoading.value = false
  }
}

const analyze = async () => {
  ElMessageBox.confirm('请确认需要解析类型？', '提示', {
    confirmButtonText: '确 认',
    cancelButtonText: '取 消'
  })
    .then(async () => {
      try {
        formLoading.value = true
        const files = uploadFile.value.map((item) => item.name)
        formData.value.text_input = aiTips(formData.value.tipType)
        const subParams = new URLSearchParams()
        subParams.append('file_paths', files.join(','))
        // subParams.append('file_paths', '客户ai测试-1.pdf')
        subParams.append('urls', '')
        subParams.append('text_input', formData?.value.text_input)
        const prefix = import.meta.env.VITE_BASE_URL + import.meta.env.VITE_API_URL
        // const prefix = 'http://47.100.191.48:9080'
        const url = prefix + '/strategy/analyze?' + subParams.toString()
        connectSSE(url, (data) => {
          try {
            console.log(data)
            const obj = JSON.parse(data)
            console.log(obj)
            console.log(obj['result type'])
            if (obj['result type'] === 'string') {
              console.log(obj['result type'])
              formLoading.value = false
              if (Array.isArray(obj.data)) {
                saveData(obj.data)
                message.success('解析成功,稍后请在相关文件列表查看')
                dialogVisible.value = false
              }
              message.error(obj.data)
              return
            }
            if (obj['result type'] === 'file') {
              // todo
            }
          } catch (error) {
            console.log(error)
          }finally {
            formLoading.value = false
          }

          // try {
          // const listStr = data
          //   .replace(/Token consumption: \d+ \(prompt: \d+, completion: \d+\)/, '')
          //   .trim()
          // const list = JSON.parse(listStr)
          // saveData(list)
          // } catch {
          //   message.error('解析失败')
          //   formLoading.value = false
          // }
        }),
          (error) => {
            console.log(error)
            formLoading.value = false
          }
      } catch (error: any) {
        formLoading.value = false
        message.error(error)
      } finally {
        //todo
      }
    })
    .catch(() => console.info('操作取消'))
}
const saveData = async (list) => {
  debugger
  if (formData.value.tipType === '1') {
    for (let index = 0; index < list.length; index++) {
      const element = list[index]
      const obj = {
        name: element.CompanyName,
        industry: element.BusinessScope,
        contact: element.BeginTime,
        phone: element.Telephone,
        address: element.Address,
        creatById: userStore.user.id
      }
      CustomerApi.createCustomer(obj)
    }
  }
  if (formData.value.tipType === '2') {
    for (let index = 0; index < list.length; index++) {
      const element = list[index]
      const obj = {
        name: element.ProjectName,
        customerName: element.CustomerName,
        startDate: element.BeginTime,
        EndTime: element.EndTime,
        creatById: userStore.user.id
      }
      ProjectApi.createProject(obj)
    }
  }
}
</script>

<style scoped>
.el-form-item {
  margin-bottom: 20px;
}
</style>
